package com.yonyou.gmmc.service.points.eventhandle;

import org.marketing.common.dto.EventDataDTO;
import org.marketing.common.event.BizEvent;
import org.marketing.common.event.EventRegisterSigninDTO;
import org.marketing.common.event.enums.EventConstant;
import org.marketing.common.event.enums.EventConstant.EventBizStep;
import org.marketing.common.event.enums.EventConstant.EventBizType;
import org.marketing.common.util.MapConverUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.yonyou.gmmc.service.points.exception.PointsException;
import com.yonyou.gmmc.service.points.model.TmPointsRule;
import com.yonyou.gmmc.service.points.service.PointsPayService;
import com.yonyou.gmmc.service.points.service.PointsRuleService;
import com.yonyou.gmmc.service.points.util.SpringUtil;

/**
 * 注册完成事件积分处理
 * 
 * @author BENJAMIN
 *
 */
public class RegisterSigninEventHandler extends AbstractEventHandle {

	private static Logger logger = LoggerFactory.getLogger(RegisterSigninEventHandler.class);

	// 注册流程
	private static EventBizType BizType = EventConstant.EventBizType.REGISTER;
	// 完成注册节点
	private static EventBizStep BizStep = EventConstant.EventBizStep.REGISTER_SIGNIN;

	// @Autowired
	// private PointsRuleService pointsRuleService;

	@Override
	protected String getHandleInfo() {
		return "处理注册流程的完成注册节点";
	}

	
	/**
	 * 主要进行数据转换
	 */
	@Override
	protected EventRegisterSigninDTO preTransform(BizEvent event) {
		EventRegisterSigninDTO o = new EventRegisterSigninDTO();
		try {
			o = (EventRegisterSigninDTO) MapConverUtil.map2POStrict(event.getEventData(), o);
			logger.info(o.toString());
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			this.backInfo = "eventData中的业务数据不能识别：" + e.getMessage();
			throw new PointsException(PointsException.EVENT_CONVERT_FAILD,"eventData中的业务数据不能识别");
		}
		return o;
	}

	/**
	 * 积分处理的逻辑
	 */
	@Override
	protected boolean pay(EventDataDTO eventData) throws PointsException{
		
		//获取到业务数据
		EventRegisterSigninDTO thisEventData = (EventRegisterSigninDTO)eventData;
		
		PointsRuleService pointsRuleService=(PointsRuleService)SpringUtil.getBean("pointsRuleService");
		
		//获取到规则
		TmPointsRule rule = pointsRuleService.getRuleByBIZ(BizType.getCodeLong(), BizStep.getCodeLong());

		if(rule!=null){
			Long points = rule.getPointsNum();
			if(points>0){
				PointsPayService pointsPayService=(PointsPayService)SpringUtil.getBean("pointsPayService");
				pointsPayService.payPointsToUser(points, thisEventData.getUserId(),thisEventData.getPhone(),
						//this.getHandleInfo(),
						rule.getRemark(),	//2017 4 13修改为规则表的remark
						String.valueOf(thisEventData.getUserId()),
						BizStep.getCode(),thisEventData.getPhone());
            }else{
            	logger.info(">>>>>>>注册积分"+points+"  不做其他操作。。。。");
            }
			
		}else{
			this.backInfo = "未找到对应的积分规则：";
			throw new PointsException(PointsException.RULE_NOTFOUND,"未找到对应的积分规则");
		}
		return false;
	}


}
